package com.nintendo.frame;

import com.nintendo.entity.pojo.Category;
import com.nintendo.mapper.CategoryDao;
import com.nintendo.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class CategoryFrame extends JFrame {

    private JTextField idField;
    private JTextField nameField;
    private JTextArea descriptionTextArea;
    private JButton addButton;
    private JButton deleteButton;
    private JButton updateButton;
    private JButton saveButton;
    private JTable table;
    private DefaultTableModel model;

    public CategoryFrame() {
        setTitle("类别管理");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(5, 2, 10, 10));

        // ID 标签和文本框
        JLabel idLabel = new JLabel("ID:");
        idField = new JTextField();
        inputPanel.add(idLabel);
        inputPanel.add(idField);

        // 名称标签和文本框
        JLabel nameLabel = new JLabel("名称:");
        nameField = new JTextField();
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);

        // 描述标签和文本域
        JLabel descriptionLabel = new JLabel("描述:");
        descriptionTextArea = new JTextArea();
        descriptionTextArea.setLineWrap(true);
        JScrollPane descriptionScrollPane = new JScrollPane(descriptionTextArea);
        inputPanel.add(descriptionLabel);
        inputPanel.add(descriptionScrollPane);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        addButton = new JButton("添加");
        deleteButton = new JButton("删除");
        updateButton = new JButton("更新");
        saveButton = new JButton("保存");

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(saveButton);

        // 添加动作监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addCategory();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteCategory();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateCategory();
            }
        });

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveCategory();
            }
        });

        // 创建表格模型
        model = new DefaultTableModel();
        model.addColumn("ID");
        model.addColumn("名称");
        model.addColumn("描述");

        // 创建表格
        table = new JTable(model);

        // 设置内容面板
        getContentPane().add(inputPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 加载数据库中的数据
        loadDataFromDatabase();
    }

    private void loadDataFromDatabase() {
        try (SqlSession session = MyBatisUtils.getSqlSession()) {
            CategoryDao mapper = session.getMapper(CategoryDao.class);
            List<Category> categories = mapper.selectAll();
            for (Category category : categories) {
                model.addRow(new Object[]{category.getId(), category.getName(), category.getDescrib()});
            }
        }
    }

    private void addCategory() {
        String idStr = idField.getText();
        String name = nameField.getText();
        String description = descriptionTextArea.getText();

        if (!idStr.isEmpty() && !name.isEmpty()) {
            int id = Integer.parseInt(idStr);
            Category category = new Category();
            category.setId(id);
            category.setName(name);
            category.setDescrib(description);
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                CategoryDao mapper = session.getMapper(CategoryDao.class);
                mapper.insert(category);
                session.commit();
            }

            model.addRow(new Object[]{id,name, description});
            clearFields();
        } else {
            JOptionPane.showMessageDialog(this, "请填写完整信息");
        }
    }

    private void deleteCategory() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int id = (Integer) model.getValueAt(selectedRow, 0);
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                CategoryDao mapper = session.getMapper(CategoryDao.class);
                mapper.deleteById(id); // 假设有一个根据ID删除的方法
                session.commit();
            }
            model.removeRow(selectedRow);
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的类别");
        }
    }

    private void updateCategory() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            String idStr = idField.getText();
            String name = nameField.getText();
            String description = descriptionTextArea.getText();

            if (!idStr.isEmpty() && !name.isEmpty()) {
                int id = Integer.parseInt(idStr);
                Category category = new Category();
                category.setId(id);
                category.setName(name);
                category.setDescrib(description);
                try (SqlSession session = MyBatisUtils.getSqlSession()) {
                    CategoryDao mapper = session.getMapper(CategoryDao.class);
                    mapper.update(category);
                    session.commit();
                }

                model.setValueAt(id, selectedRow, 0);
                model.setValueAt(name, selectedRow, 1);
                model.setValueAt(description, selectedRow, 2);
                clearFields();
            } else {
                JOptionPane.showMessageDialog(this, "请填写完整信息");
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要更新的类别");
        }
    }

    private void saveCategory() {
        // 保存类别逻辑
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < model.getRowCount(); i++) {
            sb.append("类别 ").append(i + 1).append(": ");
            sb.append("ID: ").append(model.getValueAt(i, 0)).append(", ");
            sb.append("名称: ").append(model.getValueAt(i, 1)).append(", ");
            sb.append("描述: ").append(model.getValueAt(i, 2)).append("\n");
        }
        JOptionPane.showMessageDialog(this, sb.toString());
    }

    private void clearFields() {
        idField.setText("");
        nameField.setText("");
        descriptionTextArea.setText("");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CategoryFrame().setVisible(true);
            }
        });
    }
}
